#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanXinyangPolicy(BaseTaxPolicySpider):
    name = 'henan_xinyang_paging_policy'
    
    province = '河南省'
    city = '信阳市'
    # county = '滑县'
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['信阳市浉河区人民政府', '浉河区', 'https://www.shihe.gov.cn/zfxxgk/fgwj/xzgfxwj/sz/index.html'],
            ['信阳市浉河区人民政府', '浉河区', 'https://www.shihe.gov.cn/zfxxgk/fgwj/xzgfxwj/szb/index.html'],
            ['信阳市浉河区人民政府', '浉河区', 'https://www.shihe.gov.cn/zfxxgk/fgwj/qtwj/'],
            ['信阳市浉河区人民政府', '浉河区', 'https://www.xixian.gov.cn/zwgk/zcwj/xzgfxwj/xxyxwjj/'],
            ['信阳市人民政府', '', 'https://www.xinyang.gov.cn/xxgkp/zfwj/xz/'],
            ['信阳市人民政府', '', 'https://www.xinyang.gov.cn/xxgkp/zfwj/xzw/'],
            ['信阳市人民政府', '', 'https://www.xinyang.gov.cn/xxgkp/zfwj/xzb/'],
            ['信阳市人民政府', '', 'https://www.xinyang.gov.cn/xxgkp/zfwj/xzt/'],
            ['信阳市人民政府', '', 'https://www.xinyang.gov.cn/xxgkp/zfwj/xzr/'],
        ]:
            if 'index.html' not in url:
                url += 'index.html'
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={"item": item}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//ul[@class='pageTPList' or @class='textdots' or @class='infoList' or @class='new-special-list cl newslist']/li//a[@title]/ancestor::li[string-length(string(.))>=10] |"
            "//tr//div[@class='title']//a[contains(@href, '.htm')]/ancestor::div[string-length(string(.))>=10] |"
            "//li[@class='clearfix']//a[@class]/ancestor::li[string-length(string(.))>=5]"
        )
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.pdf' in item['source_url'] or '.doc' in item['source_url']:
                continue
            else:
                print(response.url, item['source_url'])
                yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})

        if response.meta.get("is_next") is not False:
            pagecount = response.xpath("""//*[@id='pageDec']/@pagecount""").get()
            pagesize = response.xpath("""//*[@id='pageDec']/@pagesize""").get()
            total_page = math.ceil(int(pagecount) / int(pagesize))
            if not total_page:
                print(total_page, response.text)
            print(response.url, "page:", total_page)
            for page_num in range(1, int(total_page) + 1):
                yield response.follow(response.url.replace("index.", f"index_{page_num}."),
                                      callback=self.parse_list, meta={'item': prev_item, 'is_next': False}, dont_filter=True)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_xinyang_paging_policy".split())
